package hh.util;

import org.apache.tomcat.util.codec.binary.Base64;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;

public class RsaUtil {

    /**
     * 以下生成一个默认的rsa的pri pub key，使用2048bit 默认SecureRandom
     */
    public static final SecureRandom DEFAULT_SECURE_RANDOM;
    public static final KeyPair default_rsa_key_pair;

    static {
        DEFAULT_SECURE_RANDOM = new SecureRandom();
        DEFAULT_SECURE_RANDOM.nextBytes(new byte[64]);

        try {
            // 2048起步，默认随机数
            RsaAlgorithm alg = RsaAlgorithm.RS256;
            KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(alg.familyName);
            keyGenerator.initialize(alg.len, DEFAULT_SECURE_RANDOM);
            default_rsa_key_pair = keyGenerator.genKeyPair();

            // 1024，不需要随机数的方式
            //            KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
            //            generator.initialize(1024);
            //            return generator.generateKeyPair();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }




    public static void main(String[] args) {

    }



    public static byte[] getDefaultBytesPriKey() {
        return Base64.encodeBase64(default_rsa_key_pair.getPrivate().getEncoded());
    }
    public static String getDefaultStrPriKey() {
        return new String(Base64.encodeBase64(default_rsa_key_pair.getPrivate().getEncoded()));
    }


















    public static enum RsaAlgorithm {
        RS256("RSA", 2048), PS256("RSA", 2048),
        RS384("RSA", 3072), PS384("RSA", 3072),
        DEFAULT("RSA", 4096),
        ;
        private final String familyName;
        private final int len; // rsa的长度
        RsaAlgorithm(String familyName, int len) {
            this.familyName = familyName;
            this.len = len;
        }
    }
}
